<template>
  <section class="todoapp">
    <hm-header @addData="addData"></hm-header>
    <hm-main
      :list="newList"
      @changeStatus="changeStatus"
      @delData="delData"
      @changeValue="changeValue"
    ></hm-main>
    <hm-footer
      :list="newList"
      @clearAll="clearAll"
      :status="status"
      @changeList="status = $event"
    ></hm-footer>
  </section>
</template>

<script>
const obj = {
  "#/": "all",
  "#/active": "active",
  "#/completed": "completed",
};
import HmHeader from "./components/hm-header.vue";
import HmMain from "./components/hm-main.vue";
import HmFooter from "./components/hm-footer.vue";
export default {
  components: {
    HmHeader,
    HmMain,
    HmFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem("list")) || [],
      status: obj[location.hash] || "all",
    };
  },
  methods: {
    delData(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },

    changeStatus(id) {
      const obj = this.list.find((item) => item.id === id);
      obj.done = !obj.done;
    },

    addData(name) {
      if (!name) return alert("请输入内容");
      this.list.unshift({
        id: +new Date(),
        name,
        done: false,
      });
    },

    changeValue(value) {
      this.list.forEach((item) => (item.done = value));
    },

    clearAll() {
      this.list = this.list.filter((item) => item.done === false);
    },
  },
  computed: {
    newList() {
      if (this.status === "all") {
        return this.list;
      } else if (this.status === "active") {
        return this.list.filter((item) => item.done === false);
      } else {
        return this.list.filter((item) => item.done === true);
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler(newValue) {
        localStorage.setItem("list", JSON.stringify(newValue));
      },
    },
  },
};
</script>

<style></style>
